#include "MainWindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

#include <QHostAddress>



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->btnSend->setDisabled(true);

    ui->etIPAddr->setText("120.92.61.56");
    ui->etPort->setText("9100");


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnConnect_clicked()
{
    if(ui->btnConnect->text() == tr("连接")){
        QString ipText  = ui->etIPAddr->text();
        qDebug() << "IP is " << ipText;

        QString portText  = ui->etPort->text();
        qDebug() << "Port is " << portText;


        QHostAddress  hostAddr(ipText);
        mConn.startConnect(hostAddr, portText.toInt());
    }
//    else{
//        pSocket->disconnectFromHost();
//        ui->btnConnect->setText(tr("连接"));
//    }
}

void MainWindow::onHostFound()
{
    qDebug() << "Host found"  ;
}

void MainWindow::onConnected()
{
    qDebug() << "Host connected";
   // pSocket->close();
    ui->btnSend->setEnabled(true);
    ui->btnConnect->setText(tr("断开"));
}

void MainWindow::onTcpError(QAbstractSocket::SocketError error)
{

    qDebug() << "Tcp error" ;
}


void MainWindow::onTcpReadData()
{
    ui->tbRead->setText(pSocket->readAll());
}


void MainWindow::on_btnSend_clicked()
{
   QString sendText  = ui->teSend->toPlainText();
    qDebug() << sendText.toLatin1();
   if(sendText.length() > 0){
       pSocket->write(sendText.toLatin1());
       qDebug() << sendText.toLatin1();
   }
}
